<!--
 	* @author  dumeng
-->
<template>
  <div class="select-course">
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :visible.sync="visible4courseware" title="课件列表" fullscreen center @close="$emit('close')">
      <div class="clearfix">
        <el-button style="float: right;" type="primary" @click="visible = true">添加</el-button>
        <el-button style="float: right; margin-right: 10px;" @click="$emit('close')">关闭</el-button>
      </div>

      <div v-if="showCourse">
        <div class="tip"><i class="el-icon-info" />鼠标按住一行课件可进行拖动调整顺序。</div>
        <el-row class="row-th">
          <el-col :span="3" class="item-col">课件封面</el-col>
          <el-col :span="4" class="item-col">课件名称</el-col>
          <el-col :span="6" class="item-col">课件类型</el-col>
          <el-col :span="6" class="item-col">简介</el-col>
          <el-col :span="3" class="item-col">操作</el-col>
        </el-row>
        <draggable
          v-model="coursewareList"
          :animation="340"
          @end="draggableEnd"
        >
          <el-row
            v-for="(item, index) in coursewareList"
            :key="index"
            :name="item['subject']['subjectName']"
            :span="24"
            style="margin-bottom: 10px;"
            class="item-box"
          >
            <el-col :span="3" class="item-col"><el-image :preview-src-list="[item['subject'].subjectImgUrl]" :src="item['subject'].subjectImgUrl" />  </el-col>
            <el-col :span="4" class="item-col">{{ item['subject']['subjectName'] }}</el-col>
            <el-col :span="6" class="item-col">{{ item['subject']['subjectTypeValue'] }}</el-col>
            <el-col :span="6" class="item-col">
              <el-tooltip class="item" effect="dark" :content="item['subject']['subjectIntroduce']">
                <div class="etc3-1">{{ item['subject']['subjectIntroduce'] || '&nbsp;' }}</div>
              </el-tooltip>
            </el-col>
            <el-col :span="3" class="item-col">
              <el-button
                type="text"
                size="small"
                @click="handleDelete(item.id)"
              >删除</el-button>
              <el-button
            type="text"
            style="font-size: 14px"
            @click="goPractice(item)"
            >练习</el-button
          >
              </el-col>
          </el-row>
        </draggable>
      </div>
      <div v-else class="empty-box">
        暂无课件,请添加课件！
      </div>
    </el-dialog>
    <el-dialog v-if="visible" v-el-drag-dialog :close-on-click-modal="false" :visible.sync="visible" title="选择课件" fullscreen center>
      <div class="select-inner">
        <select-course-wares :course-classify="courseClassify" @handleSelect="handleSelect" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="()=>{this.visible = false;this.init()}">关 闭</el-button>
        <el-button type="primary" @click="handleComit()">确 认</el-button>
      </div>
    </el-dialog>
    
    <el-dialog
      :show-close="false"
      :visible.sync="practice"
      class="chapter-dialog"
      title="练习题"
      width="400px"
      height="600px"
      top="30vh"
      center
    >
      <el-form ref="chapterform" :model="chapterform" :rules="baserules">
        <el-form-item label="题库:" prop="questionBankId">
          <el-cascader
            ref="classify"
            :value="questionBankName"
            v-model="chapterform.questionBankId"
            :options="classifyOptions"
            style="width: 100%"
            clearable
            :props="classifyProps"
          />
        </el-form-item>

        <el-form-item label="出题数量" prop="questionNumber">
          <el-input
            v-model.number="chapterform.questionNumber"
            placeholder="请输入出题数量"
          />
        </el-form-item>
      </el-form>
      <span slot="footer"  style="margin-bottom: 30px">
        <el-button style="padding: 8px 30px" @click="practice = false"
          >取 消</el-button
        >
        <el-button
          style="padding: 8px 30px"
          type="primary"
          @click="chapterOnSubmit('chapterform')"
          >确 认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import selectCourseWares from '../SelectAudio/index'
import draggable from 'vuedraggable'
import { queryList, deleteCourseware, relevanceSubject, bySort,courseInsert,courseUpdatet,getClassifyTree } from './api'
export default {
  name: 'SelectCourse',
  directives: { elDragDialog },
  components: { draggable, selectCourseWares },
  props: {
    courseId: {
      type: String,
      default: ''
    },
    chapterParentId: {
      type: String,
      default: ''
    },
    courseClassify: {
      type: String,
      default: ''
    }

  },
  data() {
    return {
      visible4courseware: true,
      visible: false,
      coursewareList: [],
      selectList: [],
      actvieList: [],
      showCourse: true,
      practice: false,
      ctType: 0,
      chapterform: {
        courseId: "", //课程ID
        dataId: "", //关联ID。课程、章、节的ID
        questionBankId: [], //题库ID
        questionNumber: "", //出题数量
        type: "KHLXLX_KJ",
      },
      classifyOptions: [], //题库分类
      questionBankName: "",
      id:"",
      classifyProps: {
        label: "classifyName",
        value: "id",
        checkStrictly: true,
        // lazy: true,
        // lazyLoad(node, resolve) {
        //   getClassifyTree({ parentId: (node.data && node.data.id) || -1 }).then(res => {
        //     resolve(res.data.data)
        //   }).catch(() => {
        //     resolve([])
        //   })
        // }
      },
       baserules: {
        questionBankId: [
          { required: true, message: "请选择题库", trigger: "blur" },
        ],
        questionNumber: [
          { required: true, message: "请输入出题数量", trigger: "blur" },
        ],
      },
    }
  },
  created() {
    this.init()
  },
  methods: {
     goPractice(row) {
      if (row.questionBankId) {
        this.practice = true;
        this.chapterform.questionBankId = row.questionBankId;
        this.chapterform.questionNumber = row.questionNumber;
        this.id = row.questionBankRelevanceId;

        this.getClassify();
        console.log(row, "2222");
        this.ctType = 1;
      } else {
        this.ctType = 0;
        this.chapterform = {};
        this.practice = true;
        this.chapterform.dataId = row.subjectId;
        this.getClassify();
      }
    },
     /**
     * 获取题库分类
     */
    getClassify() {
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: "JNZQFL03" })
          .then(({ data }) => {
            this.classifyOptions = data.data || [];
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    chapterOnSubmit() {
      this.$refs["chapterform"].validate((valid) => {
        if (valid) {
          this.chapterform.courseId = this.courseId;
          this.chapterform.type = "KHLXLX_KJ";

          const loading = this.$loading({
            lock: true,
            text: "请稍后",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.3)",
          });
          if (this.ctType == 0) {
            this.chapterform.questionBankId =
              this.chapterform.questionBankId.length > 0
                ? this.chapterform.questionBankId[
                    this.chapterform.questionBankId.length - 1
                  ]
                : "";
            return new Promise((resolve, reject) => {
              courseInsert(this.chapterform)
                .then(() => {
                  loading.close();
                  this.$message({
                    title: "成功",
                    message: "创建成功",
                    type: "success",
                    duration: 2000,
                  });
                  this.practice = false;
                  this.init();
                })
                .catch((error) => {
                  reject(error);
                  loading.close();
                });
            });
          } else {
            console.log(this.chapterform.questionBankId);
            if (Array.isArray(this.chapterform.questionBankId)) {
              this.chapterform.questionBankId =
                this.chapterform.questionBankId.length > 0
                  ? this.chapterform.questionBankId[
                      this.chapterform.questionBankId.length - 1
                    ]
                  : "";
            }
            const from = {
              questionBankId: this.chapterform.questionBankId,
              questionNumber: this.chapterform.questionNumber,
              id: this.id,
            };
            console.log(from.questionBankId, "333");
            return new Promise((resolve, reject) => {
              courseUpdatet(from)
                .then(() => {
                  loading.close();
                  this.$message({
                    title: "成功",
                    message: "修改成功",
                    type: "success",
                    duration: 2000,
                  });
                  this.practice = false;
                  this.init();
                })
                .catch((error) => {
                  reject(error);
                  loading.close();
                });
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    init() {
      this.$nextTick(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        queryList({ courseId: this.courseId, chapterParentId: this.chapterParentId }).then(res => {
          loading.close()
          this.coursewareList = res.data.data || []
          this.showCourse = this.coursewareList.length > 0
        }).catch(loading.close())
      })
    },
    handleCancel() {
      this.$emit('close')
    },
    handleComit() {
      if (this.selectList.length > 0) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        // const subjectId = this.selectList.map(i => i.id).join(',')
        const subjectId = JSON.stringify(this.selectList.map(i => {
          const obj = {}
          obj.subjectId = i.id
          obj.subjectType = i.subjectType
          return obj
        }))
        relevanceSubject({ subjectId, courseId: this.courseId, relevanceType: 'KCGLLX_KJ', chapterParentId: this.chapterParentId }).then(res => {
          loading.close()
          this.visible = false
          this.$message({ type: 'success', message: '操作成功' })
          this.init()
        }).catch(err => {
          this.init(err)
          loading.close()
        })
      } else {
        this.$message({ type: 'warning', message: '请选择关联的课件' })
      }
    },
    handleSelect(arr) {
      this.selectList = arr
    },
    handleDelete(i) {
      this.$confirm('此操作将从当前课程中移除该课件，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        deleteCourseware({ id: i }).then(res => {
          loading.close()
          this.$message({
            type: 'success',
            message: '操作成功！'
          })
          this.init()
        }).catch(loading.close)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    draggableEnd() {
      if (this.coursewareList.length < 2) {
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      const ids = this.coursewareList.map(i => i.id).join(',')
      bySort({ ids }).then(res => {
        loading.close()
      }).catch(loading.close)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.select-course{
  position: relative;
  .tip {
    margin: 10px 0;
    font-size: 16px;
    @include font-color($mainColor)
  }
  .select-inner {
    max-height: calc(100vh - 130px);
    min-height: calc(100vh - 130px);
    position: relative;
    // overflow-y: auto;
    // &::after {
    //   content: '';
    //   height: 1px;
    //   background-color: #e2e3e8;
    //   position: absolute;
    //   bottom: 0;
    //   left: -20px;
    //   right: -20px;
    // }
  }
  .dialog-footer{
    padding-top:10px;
    position: relative;
    &::after {
      content: '';
      height: 1px;
      background-color: #e2e3e8;
      position: absolute;
      top:0 ;
      left: -20px;
      right: -20px;
    }
  }
  .item-col{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    .el-image{
      width:110px;
      height: 60px;
    }
  }

  .item-box{
    padding:15px 10px;
    border-bottom: 1px solid #ececec;
  }
  .empty-box{
    width: 100%;
    height: 300px;
    font-size: 18px;
    display:flex;
    justify-content: center;
    align-items: center;
  }
  .row-th{
    padding:10px;
    font-size: 14px !important;
    font-family: PingFangSC-Regular !important;
    font-weight: 400 !important;
    color: #a6a6a6 !important;
  }
  .el-dialog .el-dialog__body {
    padding: 10px 20px !important;
    max-height: 98vh;
    /* overflow: auto; */
         &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
   }
.el-dialog.is-fullscreen {
    width: 100%;
    margin-top: 0;
    margin-bottom: 0;
    height: 100%;
    overflow: hidden;
}
}
</style>
